package com.yst.webplugin.fieldhandler;

import com.yst.spring.context.SpringContext;
import com.yst.web.utils.BeanUtils;
import com.yst.webplugin.additional.ResultProcessor;
import com.yst.webplugin.additional.mask.MaskConfigUtil;
import com.yst.webplugin.additional.transform.TransformConfigUtil;
import com.yst.webplugin.annotation.GetModelByKey;
import com.yst.webplugin.annotation.HttpInfo;
import com.yst.webplugin.exception.ExceptionNotFindData;
import lombok.SneakyThrows;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class GetModelByKeyHandler implements IFieldHandler {
    @Override
    public boolean accept(Field field) {
        return Objects.nonNull(field.getAnnotation(GetModelByKey.class));
    }

    @SneakyThrows
    @Override
    public void handle(Field field, HttpInfo httpInfo) {
        GetModelByKey getModelByKey=field.getAnnotation(GetModelByKey.class);
        Serializable model=httpInfo.getBodyAs(getModelByKey.modelClass());

        SqlToyLazyDao sqlToyLazyDao= SpringContext.getContext().getBean(SqlToyLazyDao.class);
        List<? extends Serializable> list=
                sqlToyLazyDao.loadByIds(getModelByKey.modelClass(), BeanUtils.getFieldValue(
                model,getModelByKey.keyField(),-1));
        Optional<? extends Serializable> fullModel=list.stream().findAny();
        if (!fullModel.isPresent()) {
            throw new ExceptionNotFindData(model);
        }
        Object deleteFlag= BeanUtils.getFieldValue(fullModel,getModelByKey.deleteTimeField(),null);
        if (Objects.nonNull(deleteFlag)){
            throw new ExceptionNotFindData(model);
        }
        ResultProcessor resultProcessor=new ResultProcessor().addAllFieldMaskConfig(MaskConfigUtil.fromField(field))
                .addAllTransformConfig(TransformConfigUtil.fromField(field))
                .addAllTransformConfig(TransformConfigUtil.fromClass(getModelByKey.modelClass()))
                .disableField(getModelByKey.disabledFields());
        resultProcessor.deepProcess(fullModel.get());
        httpInfo.writeResult(fullModel.get());
    }
}
